// pages/addToStore/addToStore.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
const storage = require('../../utils/storage');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    // 底部菜单高度
    tabbarHeight: app.globalData.tabbarHeight,
    BASEURLWWW:constant.BASEURLWWW,
    BASEURL: constant.BASEURL,
    // 表单，
    form:{
      describe: '',
      matter_price: [],
      matter_pic: [
        {url: "",sort:0}
      ],
      matter_video: ""
    },
    // 拖拽区域
    movableArea:{
      width: 690,
      height: 220
    },
    imageWitdh: null,
    // 图片拖拽
    images:[],
    pointsArr: [],
    currentImg: '',
    currentIndex: null,
    hidden: false,
    flag: true,
    x: null,
    y: null,
    scrollTop:0, // 滚动条距离顶部的距离
    // 开关
    switch1Checked:false,
    // 公开展示
    shoWswitchChecked:false,
    // 价格id数组
    priceArr: [],
    // 图片相关
    tempFilePaths: []
  },
  onLaunch:function(){

  },
  // 监听滚动
  onPageScroll:function(e){
    this.data.scrollTop = e.scrollTop;
  },
  // 显示操作菜单
  showActionSheet(){
    let that = this
    wx.showActionSheet({
      itemList: ['上传图片', '上传视频'],
      success (res) {
        let images = that.data.images
        let count = 9 - images.length
        if(res.tapIndex == 0){ // 上传图片
          wx.chooseImage({
            count, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              console.info(res)
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              let tempFilePaths = res.tempFilePaths
              tempFilePaths.forEach(item => {
                that.uploadFile(item)
              })
            }
           })
        }else{ // 上传视频
          wx.chooseVideo({
            sourceType: ['album','camera'],
            maxDuration: 60,
            camera: 'back',
            success(res) {
              that.uploadFile(res.tempFilePath)
              console.log(res.tempFilePath)
            }
          })
        }
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })    
  },
  // 上传操作
  uploadFile(item){
    let that = this
    let images = this.data.images
    wx.uploadFile({
      url: `${that.data.BASEURL}/myfile/wechat`, //仅为示例，非真实的接口地址
      filePath: item,
      name: 'file',
      header:{
        'Authorization': 'Bearer '+ wx.getStorageSync(storage.LOCAL_JWT_KEY),
        'Deviceid': 'loveqing'
      },
      formData: {},
      success (res){
        let jsonObj = JSON.parse(res.data)
        console.info(jsonObj)
        if(jsonObj.code == 0){
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          })
          images.push({url:jsonObj.data.uri})
          that.setData({
            images
          })
          that.handleComputedImage()
        }else{
          wx.showToast({
            title: jsonObj.msg,
            icon: 'error'
          })
          if(jsonObj.code == 50005){
            setTimeout(()=>{
              wx.reLaunch({
                url: '/pages/login/login',
              })
            },500)
          }
        }
      }
    })
  },
  // 计算图片位置
  handleComputedImage(){
    let movableArea = this.data.movableArea
    let images = this.data.images
    if(images.length>0){
      // 计算可拓展区域
      if(images.length>=9){
        movableArea.height = 690
      }else{
        movableArea.height = Math.ceil((images.length+1)/3)*230
      }
      images.forEach((item,index) => {
        item.id = index
      })
      this.setData({
        'movableArea.height': movableArea.height,
        images,
      })
    }else{
      this.setData({
        'movableArea.height': 220,
        images,
      })
    }
    console.info(images)
  },
  // 删除图片
  deleteMovableView(e){
    let images = this.data.images
    let index = e.currentTarget.dataset.index
    images.splice(index,1);
    console.info(images)
    this.handleComputedImage(images)
  },
  // 长按
  handleLongTap(e){
    let that = this;
    let query = wx.createSelectorQuery();
    query.select('.coverWrap').boundingClientRect(function (rect) {
      console.info(rect.width)
      that.setData({
        imageWitdh: rect.width
      })
    }).exec();
    let nodesRef = query.selectAll(".coverWrap");
    nodesRef.fields({
      dataset: true,
      rect: true
    }, (result) => {
      console.info(result)
      that.setData({
        pointsArr: result
      })
    }).exec()
    this.setData({
      currentImg: e.currentTarget.dataset.url,
      currentIndex: e.currentTarget.dataset.index,
      hidden: false,
      flag: true,
      x: e.currentTarget.offsetLeft,
      y: e.currentTarget.offsetTop
    })
    console.info("长按",e)
  },
  // 移动的过程中
  handleTouchMove:function(e){
    let x = e.touches[0].pageX;
    let y = e.touches[0].pageY;
   // 首先先获得当前image-choose-container距离顶部的距离
    let that = this;
    wx.createSelectorQuery().selectAll('.coverWrap').boundingClientRect(function (rect) {
      let top = rect[0].top;
      y = y - that.data.scrollTop - top;
      that.setData({
        x: x - that.data.imageWitdh / 2 > 0 ? x - that.data.imageWitdh / 2:0,
        y: y - that.data.imageWitdh / 2 > 0 ? y - that.data.imageWitdh / 2:0,
        // x: x,
        // y: y,
      })

    }).exec()
  },
  // 移动结束的时候
  handleTouchEnd:function(e){
    if (!this.data.flag) {
      // 非长按情况下
      return;
    }
    let  x = e.changedTouches[0].pageX;
    let y = e.changedTouches[0].pageY - this.data.scrollTop;
    const pointsArr = this.data.pointsArr;
    let data = this.data.images;
    for (var j = 0; j < pointsArr.length; j++) {
      const item = pointsArr[j];
      if (x > item.left && x < item.right && y > item.top && y < item.bottom) {
        const endIndex = item.dataset.index;
        const beginIndex = this.data.currentIndex;
        //临时保存移动的目标数据
        let temp = data[beginIndex];
        //将移动目标的下标值替换为被移动目标的下标值
        data[beginIndex] = data[endIndex];
        //将被移动目标的下标值替换为beginIndex
        data[endIndex] = temp;
      }
    }
    console.info(data)
    this.setData({
      images: data,
      hidden: true,
      flag: false,
      currentImg: ''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    // this.getPriceList();
    
  },
  // 开关
  switchChange(e){
    console.log(e);
    this.setData({
      switchChecked:e.detail.value
    })
  },
  // 获取价格列表
  getPriceList(){
    let form = this.data.form;
    let priceArr = [];
    api.priceList().then(res => {
      if(res.code == 0){
        res.data.data.forEach(item => {
          item.price = '';
          form.matter_price.push(item);
          priceArr.push(item.price_id);
        })
        this.setData({
          form,
          priceArr
        })
      }
    })
  },
  // 获取产品描述
  getDescribe:function(e){
    let describe = e.detail.value;
    this.setData({
      'form.describe':describe
    })
  },
  // 上传图片
  upload:function(){
    let that = this;
    let tempFilePaths = this.data.tempFilePaths;
    let BASEURL = this.data.BASEURL;
    wx.chooseImage({
      count: 9 - tempFilePaths.length, // 最多可以选择9张
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        console.log(res);
        // tempFilePath可以作为img标签的src属性显示图片
        wx.uploadFile({
          url: BASEURL+'/myfile/wechat', //仅为示例，非真实的接口地址
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test',
            'type': 0,
            'thumb': 1
          },
          success (res){
            console.log(res);
            let jsonObj = JSON.parse(res.data)
            if(jsonObj.code == 0){
              tempFilePaths.push(jsonObj.data);
              that.setData({
                tempFilePaths
              })
            }
          }
        })
      }
    })
  },
  // 获取价格
  getPrice:function(e){
    let price_id = e.currentTarget.dataset.id;
    let price = parseFloat(e.detail.value);
    let form = this.data.form;
    let priceArr = this.data.priceArr;
    let index = priceArr.indexOf(price_id);
    form.matter_price[index].price = price;
    this.setData({
      form
    })
    
  },
  // 入库
  addHandle:function(){

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
   // 返回到首页
  back:function(){
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },
  
})